<?php

namespace App\Admin\Controllers\Scm;

use App\Models\Scm\Building;
use App\Models\Scm\Org;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;

class BuildingController extends AdminController
{
    protected $title = '建筑';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(Building::with(['org']), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('name', '建筑');
//            $grid->column('org_name', '组织')->display(function () {
//                return $this->org->name ?? '-';
//            });
            $grid->column('org_paths_index', '组织路径')->display(function () {
                return $this->org->paths_index ?? '-';
            });

            $grid->column('building_type', '建筑类型')->using(
                \collect(\data_get(Building::staticEnums(), 'building_type', []))->pluck('text', 'id')->toArray()
            );
//            $grid->column('floor', '楼层');
//            $grid->column('parking_space_capacity', '可停车数量')->display(function () {
//                if (!in_array($this->building_type, [
//                    Building::BUILDING_TYPE_PARKING_LOT,
//                    Building::BUILDING_TYPE_PARKING_SPACE,
//                    Building::BUILDING_TYPE_PARKING_GARAGE
//                ])) {
//                    return '-';
//                }
//                return $this->parking_space_capacity;
//            });
            $grid->column('status', '状态')->using(
                \collect(data_get(Org::staticEnums(), 'status', []))->pluck('text', 'id')->toArray()
            )->label(
                \collect(data_get(Org::staticEnums(), 'status', []))->pluck('label', 'id')->toArray()
            );
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Building(), function (Show $show) {
            $show->field('id');
            $show->field('name');
            $show->field('display_name');
            $show->field('building_type');
            $show->field('building_use_type');
            $show->field('floor');
            $show->field('building_area');
            $show->field('chargeable_area');
            $show->field('parking_space_capacity');
            $show->field('use_status');
            $show->field('sell_status');
            $show->field('lease_status');
            $show->field('introduce');
            $show->field('config_data');
            $show->field('detail');
            $show->field('org_id');
            $show->field('status');
            $show->field('extra_data');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(Building::with(['org']), function (Form $form) {
            if ($form->isCreating()) {
                $form->embeds('org', '', function (Form\EmbeddedForm $form) {
                    $form->select('parent_id', '上级组织')->required()->options(function () {
                        return Org::selectOptions(null, '顶级');
                    })->saving(function ($v) {
                        return (int)$v;
                    })->rules('required', [
                        'required' => '上级组织，必填',
                    ]);
//                    $form->text('name', '组织名称')->rules('max:100', [
//                        '组织名称，最大长度100'
//                    ]);
                    $form->number('sort', '组织排序')->default(1)->rules('integer|min:1', [
                        'integer' => '组织排序，必须为整数',
                        'min' => '组织排序，最小值为1'
                    ])->min(1);
                    $form->hidden('relation_class_name')->value(Org::RELATION_CLASS_NAME_BUILDING);
                });
            }
            $form->display('id');
            if ($form->isEditing()) {
//                $form->display('org.name', '组织名称');
                $form->display('org.paths_index', '组织路径');
            }
            $form->text('name', '建筑名称')->required()->rules(
                [
                    'required',
                    'max:100',
                    function ($attribute, $value, $fail) {
                        $state = DB::table('scm_orgs')->where('parent_id', '=', \request()->input('org.parent_id', 0))->where('name', '=', $value)->exists();
                        if ($state) {
                            return $fail('该组织已经存在');
                        }
                    },
                ],
                [
                    'required' => '建筑名称，必填',
                    'max' => '建筑名称，最大长度100',
                ]
            );
//            $form->text('display_name', '显示名称')->rules('max:100', ['max' => '显示名称，最大长度100']);
            $form->select('building_type', '建筑类型')->required()->options(
                \collect(\data_get(Building::staticEnums(), 'building_type', []))->pluck('text', 'id')->toArray()
            );
            $form->number('parking_space_capacity', '可停车数量')->rules('integer|min:0', [
                'integer' => '车位数量，必须为整数',
                'min' => '车位数量，最小为0',
            ])->default(0)->min(0);
            $form->number('floor', '楼层')->rules('integer', [
                'integer' => '楼层，必须为整数',
            ])->default(1);
            $form->number('building_area', '建筑面积')->default(0.00)->required()->min(0);
            $form->number('chargeable_area', '缴费面积')->default(0.00)->required()->min(0);
            $form->textarea('introduce', '简介')->rules('max:1000', [
                'max' => '简介，最大长度1000',
            ]);
            $form->ueditor('detail', '详情');
            $form->display('created_at');
            $form->display('updated_at');

            $form->saved(function (Form $form, $result) {
                if ($result) {
                    $model = $form->repository()->model()->refresh();
                    if ($model->org) {
                        if (\optional($model->org)->id) {
                            if (\str($model->org->name)->isEmpty()) {
                                $model->org->name = $model->name;
                            }
                            $model->org->update();
                            Org::extendRefreshRelationClassInstance($model->org->id);
                            Org::extendRefreshPaths($model->org->id, true);
                            Org::extendSaveOrder(0);
                        }
                    }
                }
            });
        });
    }
}
